/*
 * 后台商品选择组件
 *
 *
 */
var ProdcutSelectorType = {
    MultiSelectProduct: 'multiSelectProduct', //多选商品无规格
    MultiSelectSpecs: 'multiSelectSpecs', //多选商品规格
    MultiSelectProductSpecs: 'multiSelectProductSpecs', //多选商品，多选规格
    SingleProductSpecs: 'singleProductSpecs', //单选商品，多选规格
    TableProductSpec: 'tableProductSpec',    //支持Table的选择器
    TablePackageProduct: 'tablePackageProduct',    //支持Table的选择器
    AcitivityProductSpecSelector: 'acitivityProductSpecSelector'
};
var FaceboxSelector = new Class({
    Extends: Facebox,
    initialize: function(options) {
        this.parent(options);
    }
});
var ProdcutSelector = new Class({
    Implements: Options,
    Binds: ['onRemoveItem', 'onFormSubmit', 'onSelectHandleClick',
            'onSelectorShown', 'searchProduct', 'bindItems', 'onSelectorHide'],
    selector: null,
    options: {
        title: '选择商品',
        selectorType: '',
        selectorService: 'productsearch.php',
        checkBoxName: '',
        selectorWidth: 700,
        itemWidth: '',
        listLength: 0,
        minLength: 0, //至少选择几个
        setDefault: false, //是否显示默认列表项( 显示 “所有商品” )
        defaultText: '所有商品',
        onAddItem: null,
        onRemoveItem: null,
        onSelecotrShown: null,
        onSelectorHide: null,
        onProductSearched: null,
        onSelected: null
    },
    initialize: function(form, container, handle, options) {
        this.setOptions(options);
        this.form = $(form);
        this.list = $(container);

        this.selectorHandle = $(handle);
        this.selector = new FaceboxSelector({
            width: this.options.selectorWidth,
            showFooter: false,
            onShown: this.onSelectorShown,
            onClose : this.onSelectorHide
        });
        this.selectorHandle.addEvent('click', this.onSelectHandleClick);
        this.form.addEvent('submit', this.onFormSubmit);
        this.list.getElements('a').addEvent('click', this.onRemoveItem);
        if (this.options.setDefault && this.list.getChildren().length == 0) {
            this.setDefaultItem();
        }
    },
    onSelectorShown: function(e) {
            this.getSelectorElement('input[name=searchBtn]').addEvent('click', this.searchProduct);
            this.getSelectorElement('input[name=submitBtn]').addEvent('click', this.bindItems);
            this.getSelectorElement('input[name=cancelbtn]').addEvent('click', this.selector.close.bind(this.selector));
            new OverText($('productName')).show();
            if (this.options.onSelectorShown != null) {
                this.options.onSelectorShown(e);
            }
        },
    onSelectorHide: function(e) {
            this.getSelectorElements('input[type=button]').each(function(button) {
                button.removeEvent('click');
            });
            if (this.options.onSelectorHide != null) {
                this.options.onSelectorHide(e);
            }
        },
    addItem: function(item) {
        this.removeDefaultItem();
        var listItem = this.createElemet(item).inject(this.list);
        if (this.options.onAddItem != null) {
            this.options.onAddItem(listItem, this);
        }
    },
    clear: function() {
        this.list.empty();
    },
    createElemet: function(item) {
        var el = new Element('li').set('ident', item.get('ident'));
        new Element('a').set('href', 'javascript:;').set('html', 'del').addEvent('click', this.onRemoveItem).inject(el);
        new Element('span').set('html', this.createItemCaption(item)).inject(el);
        return el;
    },
    createItemCaption: function(item) {
        return item.get('caption');
    },
    getResultCheckBoxes: function() {
        var els = [];
        this.getSelectorElements('input[type=checkbox]').each(function (item) {
            if (item.checked && item.name == this.options.checkBoxName) {
                els.push(item);
            }
        }, this);
        return els;
    },
    getSelectorElement: function(arg) {
        return this.selector.faceboxEl.getElement(arg);
    },
    getSelectorElements: function(arg) {
        return this.selector.faceboxEl.getElements(arg);
    },
    itemSize: function() {
        var childs = this.list.getChildren();
        var length = childs.length;
        return childs.indexOf(this.list.getElement('.allProduct')) == -1 ? length : length - 1;
    },
    createServiceUrl: function() {
        var urlParams = [
            'a=' + this.options.selectorType,
            'checkBoxName=' + this.options.checkBoxName,
            'itemWidth=' + this.options.itemWidth,
            'showAll=' + (this.options.showAll ? '1' : '0')
        ];
        var url = this.options.selectorService + '?' + urlParams.join('&');
        return url;
    },
    createSearchServiceUrl: function() {
        var urlParams = [];
        this.getSelectorElements('.searchParam').each(function(item) {
            urlParams.push(item.get('name') + '=' + item.get('value'));
        });
        return this.createServiceUrl() + '&' + urlParams.join('&') + '&searchProduct=1';
    },
    setDefaultItem: function() {
        if (!this.options.setDefault) {
            return;
        }
        if (!this.defaultItem || this.defaultItem == null) {
            this.defaultItem = new Element('li').set('id', 'allProduct').set('class', 'allProduct').set('html', this.options.defaultText).inject(this.list);
        }
    },
    removeDefaultItem: function() {
        if (this.defaultItem != null) {
            this.defaultItem.dispose();
            this.defaultItem = null;
        }
    },
    onRemoveItem: function(e) {
        var listItem = $(e.target).getParent();
        if (this.options.onRemoveItem != null) {
            this.options.onRemoveItem(listItem, this);
        }
        listItem.dispose();
        if (this.list.getChildren().length == 0) {
            this.setDefaultItem();
        }
    },
    onFormSubmit: function(e) {
        this.form.getElements('input[name="' + this.options.checkboxName + ']"').dispose();
        
        this.list.getChildren().each(function(item) {
            new Element('input', { type:  'hidden',
                                   name:  this.options.checkBoxName,
                                   value: item.get('ident')
                                  }).inject(this.form);
        }, this);
    },
    onSelectHandleClick: function(e) {
        this.selector.show(this.options.title, '', this.createServiceUrl());
    },
    searchProduct: function(e) {
        var self = this;
        var el = $('productlist').empty();
        el.set('load', {
            onSuccess: function(response) {
                if (self.options.onProductSearched != null) {
                    self.options.onProductSearched(el, response);
                }
                self.productSearched(el, response);
            }
        });
        el.load(this.createSearchServiceUrl());
    },
    productSearched: function(el, response) {},
    bindToList: function() {
        var checkBoxes = this.getResultCheckBoxes();
        if (checkBoxes.length == 0) {
            return false;
        }
        if (this.options.listLength > 0) {
            var selectedCount = checkBoxes.length + this.list.getChildren().length;
            if (this.defaultItem != null) {
                selectedCount--;
            }
            if (selectedCount  > this.options.listLength) {
                alert('对不起，列表最多只能选择 ' + this.options.listLength + ' 项!');
                return false;
            }

            if (this.options.minLength > 0 && selectedCount < this.options.minLength) {
                alert('对不起，列表至少选择 ' + this.options.minLength + ' 项!');
                return false;
            }
        }
        if (this.options.onSelected != null) {
            this.options.onSelected(this);
        }
        if (this.defaultItem != null) {
            this.removeDefaultItem();
        }
        var idents = [];
        this.list.getChildren().each(function(item) {
            idents.push(item.get('ident'));
        });
        checkBoxes.each(function(item) {
            if (item.checked && !idents.contains(item.get('ident'))) {
                this.addItem(item);
            }
        }, this);
        return true;
    },
    bindItems: function(e) {
        if (this.bindToList()) {
            this.selector.close();
        }
    }
});
//多选商品无规格
var MultiSelectProductSelector = new Class({
    Extends: ProdcutSelector,
    initialize: function(form ,container, handle, options) {
        this.parent(form, container, handle, options);
        this.options.selectorType = ProdcutSelectorType.MultiSelectProduct;
    },
    onSelectorShown: function(e) {
        this.parent(e);
        this.selectAllBtn = new Element('input', {
            type: 'button',
            value: '选择全部'
        }).addClass('button')
          .addEvent('click', this.selectAllItems.bind(this))
          .inject(this.getSelectorElement('.footer'), 'top');
    },
    selectAllItems: function(e) {
        this.getSelectorElements('input[type=checkbox').each(function(item) {
            if (!item.disabled) {
                item.checked = !!!this.checkState;
            }
        }, this);
        this.checkState = !this.checkState;
        if (this.checkState) {
            this.selectAllBtn.set('value', '取消全选');
        } else {
            this.selectAllBtn.set('value', '选择全部');
        }
    }
});

//商品规格选取
var MultiSelectSpecsSelector = new Class({
    Extends: ProdcutSelector,
    initialize: function(form, container, handle, options) {
        if (!options || !options.selectorWidth) {
            options.selectorWidth = 600;
        }
        this.parent(form, container, handle, options);
        this.options.selectorType = ProdcutSelectorType.MultiSelectSpecs;
    },
    getModelCheckboxes: function (el) {
        return this.getSelectorElements('input[name=modelCheckbox]');
    },
    onSelectorShown: function(e) {
        this.getSelectorElement('input[name=searchBtn]').addEvent('click', this.searchModel.bind(this));
        this.getSelectorElement('input[name=submitBtn]').addEvent('click', this.bindItems);
        this.getSelectorElement('input[name=cancelbtn]').addEvent('click', this.selector.close.bind(this.selector));
        this.modelList = $('modelList');
        new OverText($('modelName')).show();
        if (this.options.onSelectorShown != null) {
            this.options.onSelectorShown(e);
        }
        this.clearBtn = new Element('input', {
            type: 'button',
            value: '清空已选'
        }).addClass('button')
          .addEvent('click', this.clearSelected.bind(this))
          .inject(this.getSelectorElement('.footer'), 'top');
        this.continueBtn = new Element('input', {
            type: 'button',
            value: '选中继续'
        }).addClass('button')
          .addEvent('click', this.selectedContinue.bind(this))
          .inject(this.getSelectorElement('.footer'), 'top');
    },
    clearSelected: function(e) {
        this.selectorHandle.value = '';
        $('modelName').focus();
    },
    searchModel: function(e) {
        var self = this;
        var el = this.modelList.empty();
        el.set('load', {
            onSuccess: function(response) {
                if (self.options.onModelSearched != null) {
                    self.options.onModelSearched(el, response);
                }
                self.modelSearched(el, response);
            }
        });
       
       el.load(this.createSearchServiceUrl());
    },
    createSearchServiceUrl: function() {
        var urlParams = [];
        this.getSelectorElements('.searchParam').each(function(item) {
            urlParams.push(item.get('name') + '=' + item.get('value'));
        });
        return this.createServiceUrl() + '&' + urlParams.join('&') + '&searchModel=1';
    },
    modelSearched: function(el, response) {
        var self = this;
        this.searched = true;
    },
    selectedContinue: function(e) {
        var models = [];
        this.modelList.getElements('input[checked]').each(function(el) {
            models.push($(el).get('value'));
        });
        if (models.length > 0){
            if ('' != this.selectorHandle.value) {
                this.selectorHandle.value = this.selectorHandle.value + ',';
            }
            this.selectorHandle.value += models.join(',');
            this.modelList.empty();
            $('modelName').value = '';
            $('modelName').focus();
        }
    }
});

//多选商品，多选规格
var MultiSelectProductSpecsSelecotr = new Class({
    Extends: ProdcutSelector,
    initialize: function(form ,container, handle, options) {
        if (!options || !options.selectorWidth) {
            options.selectorWidth = 600;
        }
        this.parent(form, container, handle, options);
        this.options.selectorType = ProdcutSelectorType.MultiSelectProductSpecs;
    },
    getProductCheckboxes: function (el) {
       return this.getSelectorElements('input[name=productCheckbox]');
    },
    onSelectorShown: function(e) {
        this.parent(e);
        $('productSku') && new OverText($('productSku')).show();
        this.continueBtn = new Element('input', {
            type: 'button',
            value: '选中继续'
        }).addClass('button')
          .addEvent('click', this.seelctedContinue.bind(this))
          .inject(this.getSelectorElement('.footer'), 'top');
    },
    onSelectorHide: function(e) {
        this.parent(e);
        this.continueBtn.removeEvent('click');
        this.continueBtn.dispose();
        delete this.continueBtn;
        if (this.searched) {
            this.getProductCheckboxes().each(function(item) {
                item.removeEvent('click');
                item.subcheckboxes.each(function(checkbox) {
                    checkbox.removeEvent('click');
                });
            });
            this.searched = false;
        }
    },
    seelctedContinue: function(e) {
        if (!this.bindToList()) {
            return;
        }
    },
    getItemProperty: function(item, name) {
        var value = item.get(name);
        if (null == value) {
            return '';
        }
        return value;
    },
    createItemCaption: function(item) {
        return item.get('productName') + ' ' + this.getItemProperty(item, 'specValue')
                                       + ' ' + this.getItemProperty(item, 'sku')
                                       + ' <span class="color-block" style="background:url('
                                       + this.getItemProperty(item, 'colorImage')
                                       + ') ' + this.getItemProperty(item, 'colorValue') + '"></span>';
    },
    productSearched: function(el, response) {
        this.parent(el, response);
        this.searched = true;
        this.getProductCheckboxes().each(function(item) {
            item.subcheckedCount = 0;
            item.productSpecsWrapper = item.getParent().getElement('.productSpecsWrapper');
            item.subcheckboxes = item.productSpecsWrapper.getElements('input[type=checkbox]');
            item.addEvent('click', function(e) {
                item.subcheckboxes.each(function(checkbox) {
                    checkbox.checked = item.checked;
                });
                item.subcheckedCount = item.checked ? item.subcheckboxes.length : 0;
            });
            item.subcheckboxes.each(function(checkbox) {
                checkbox.addEvent('click', function(e) {
                    if (checkbox.checked) {
                        item.subcheckedCount++;
                    } else {
                        item.subcheckedCount--;
                    }
                    item.checked = item.subcheckedCount == item.subcheckboxes.length;
                });
            });
        });
        this.hideDefaultSpec();
    },
    hideDefaultSpec: function() {
        var captionItems = {};
        this.getSelectorElements('input[type=checkbox]').each(function(item) {
            if (item.name == this.options.checkBoxName) {
                var key = item.get('productName');
                if (!captionItems[key]) {
                    captionItems[key] = [];
                }
                captionItems[key].push(item.getParent('li').getElement('.caption'));
            }
        }, this);
        for(var key in captionItems) {
            var captionItem = captionItems[key];
            if (captionItem.length == 1 && captionItem[0].get('html').indexOf('默认规格') != -1) {
                captionItem[0].getParent('.productSpecsWrapper').hide();
            }
        }
    }
});
//单选商品，多选规格
var SingleProductSpecsSelector = new Class({
    Extends: MultiSelectProductSpecsSelecotr,
    initialize: function(form ,container, handle, options) {
        if (!options || !options.selectorWidth) {
            options.selectorWidth = 570;
        }
        this.parent(form, container, handle, options);
        this.options.selectorType = ProdcutSelectorType.SingleProductSpecs;
    }
});
//支持Table的选择器
var TableProductSpecSelector = new Class({
    Extends: MultiSelectProductSpecsSelecotr,
    options : {
        onCreateElemet:null
    },
    initialize: function(form ,container, handle, options) {
        this.parent(form, container, handle, options);
        //this.list.hide();
    },
    addItem: function (item) {
        this.removeDefaultItem();
        var listItem = this.createElemet(item).inject(this.list);
        if (this.options.onAddItem != null) {
            this.options.onAddItem(listItem, this);
        }
    },
    createElemet: function (item) {
        if (this.options.onCreateElemet != null) {
            el = this.options.onCreateElemet(item, this);
        }
        return el;
    }
});

var TablePackageProductSpecSelector = new Class({
    Extends: TableProductSpecSelector,
    options : {
        onCreateElemet:null
    },
    initialize: function(form ,container, handle, options) {
        this.parent(form, container, handle, options);
        this.options.selectorType = ProdcutSelectorType.TablePackageProduct;
        //this.list.hide();
    },
    addItem: function (item) {
        this.removeDefaultItem();
        var listItem = this.createElemet(item).inject(this.list);
        
        if (this.options.onAddItem != null) {
            this.options.onAddItem(listItem, this);
        }
    },
    createElemet: function (item) {
        if (this.options.onCreateElemet != null) {
            el = this.options.onCreateElemet(item, this);
        }
        return el;
    },
    createItemCaption: function(item) {
        return item.get('caption');
    },
    onSelectorShown: function(e) {
        this.parent(e);
        $('masterProductName') && new OverText($('masterProductName')).show();
    }
});

//单商品多规格  团购 套装
var SingleProductMultiSpecSelector = new Class({
    Extends:MultiSelectProductSpecsSelecotr,
    bindToList: function() {
        if (this.getResultCheckBoxes().length == 0) {
            return false;
        }
        if (this.defaultItem != null) {
            this.removeDefaultItem();
        }
        this.clear();
        return this.parent();
    },
    productSearched: function(el, response) {
        var self = this;
        var lastCheckedRadio = null;
        this.getProductCheckboxes().each(function(item) {
            item.set('type', 'radio');
            item.subcheckedCount = 0;
            item.subcheckboxes = self.getSubCheckBoxs(item);
            item.addEvent('click', function(e) {
                if (lastCheckedRadio != item) {
                    if (lastCheckedRadio != null) {
                        self.getSubCheckBoxs(lastCheckedRadio).each(function(i){
                            i.checked = false;
                        });
                        lastCheckedRadio.subcheckedCount = 0;
                    }
                    lastCheckedRadio = item;
                }
                item.subcheckboxes.each(function(checkbox) {
                    checkbox.checked = item.checked;
                });
                item.subcheckedCount = item.subcheckboxes.length;
            });

            item.subcheckboxes.each(function(checkbox) {
                checkbox.addEvent('click', function(e) {
                    if (checkbox.checked) {
                        item.subcheckedCount++;
                    } else {
                        item.subcheckedCount--;
                    }
                    if (item.subcheckedCount == 0) {
                        item.checked = false;
                    }
                    if (lastCheckedRadio != item) {
                        if (lastCheckedRadio != null) {
                            self.getSubCheckBoxs(lastCheckedRadio).each(function(i){
                                i.checked = false;
                            });
                            lastCheckedRadio.subcheckedCount = 0;
                        }
                        lastCheckedRadio = item;
                        item.checked = true;
                    }
                });
            });
        });
    },
    getSubCheckBoxs:function(item) {
        return item.getParent().getElement('.productSpecsWrapper').getElements('input[type=checkbox]');
    }
});

